package net.socket.broad;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @projectName: java-sample
 * @description:
 * @author: Adam
 * @create: 2020-01-06 10:17
 **/

public class ServerThread implements Runnable {

   //定义当前线程所处理的socket
    Socket s = null;
    //该线程所处理的socket对应的输入流
    BufferedReader br = null;
    public ServerThread(Socket s) throws IOException {
        this.s = s;
        //初始化该socket对应的输入流
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    }

    @Override
    public void run() {
       try {
           String content = null;
           //采用循环不断地从Socket中读取客户端发送来的数据
           while ((content = readFromClient()) !=null){
               //遍历socketList中的每个socket
               //将读到的内容向每个socket发送一个
               for (Socket s:MyServer.scoketList){
                   PrintStream ps = new PrintStream(s.getOutputStream());
                   ps.println(content);
               }
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    }


    //定义服务客户端数据的方法
    private String readFromClient(){
        try {
            return br.readLine();
        }catch (IOException e){
            //如果捕获到异常，则表明该socket对应的客户端已经关闭
            //删除该socket
            MyServer.scoketList.remove(s);
        }
        return null;
    }
}
